package com.test.study.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Logger;

import org.junit.Test;

public class JdbcCRUD2 {
	private static final Logger log = Logger.getLogger(JdbcCRUD2.class.getName());

	@Test
	public void save() {
		Connection connection = null;
		PreparedStatement statement = null;
		String sql = "insert into user_test values(null,?,?,?,?)";
		try {
			connection = JdbcUtils.getConnection();
			statement = connection.prepareStatement(sql);
			statement.setString(1, "huyong");
			statement.setString(2, "!QAZ2wsx3edc");
			statement.setString(3, "勇哥");
			statement.setInt(4, 200);
			int count = statement.executeUpdate();
			log.info("save count==> " + count);
		} catch (Exception e) {
		} finally {
			JdbcUtils.close(connection, statement);
		}

	}

	@Test
	public void update() {
		Connection connection = null;
		PreparedStatement statement = null;
		String sql = "update user_test set password=? where id=?";
		try {
			connection = JdbcUtils.getConnection();
			statement = connection.prepareStatement(sql);
			statement.setString(1, "@WSX3edc!QAZ");
			statement.setString(2, "6");
			int count = statement.executeUpdate();
			log.info("update count==> " + count);
		} catch (Exception e) {
		} finally {
			JdbcUtils.close(connection, statement);
		}
	}

	@Test
	public void find() {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		String sql = "select * from user_test where username=? and password=?";
		try {
			connection = JdbcUtils.getConnection();
			statement = connection.prepareStatement(sql);
			statement.setString(1, "huyong");
			statement.setString(2, "@WSX3edc!QAZ");
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String username = resultSet.getString("username");
				String password = resultSet.getString("password");
				String nickname = resultSet.getString("nickname");
				int age = resultSet.getInt("age");
				log.info(id + "\t" + username + "\t" + password + "\t" + nickname + "\t" + age);
			}
		} catch (Exception e) {
		} finally {
			JdbcUtils.close(connection, statement, resultSet);
		}

	}

	@Test
	public void delete() {
		Connection connection = null;
		PreparedStatement statement = null;
		String sql = "delete from  user_test  where id=?";
		try {
			connection = JdbcUtils.getConnection();
			statement = connection.prepareStatement(sql);
			statement.setString(1, "6");
			int count = statement.executeUpdate();
			log.info("delete count==> " + count);
		} catch (Exception e) {
		} finally {
			JdbcUtils.close(connection, statement);
		}
	}

}
